// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
const doubanbook = require('doubanbook')
const cheerio = require('cheerio')

cloud.init()

async function getdouban(isbn) {
  //9787121336775
  
  const url = 'https://search.douban.com/book/subject_search?search_text='+isbn+'&cat=1001' 
  //console.log(url)
  let searchInfo = await axios.get(url)

  // 获取windeow._DATA_="{.*}"/
  let reg = /window\.__DATA__ = "(.*)"/
  if (reg.test(searchInfo.data)) {
      //console.log(RegExp.$1)
      let searchdata = doubanbook(RegExp.$1)[0]
      //console.log(searchdata.title,searchdata.rating)
      let detailPage = await axios.get(searchdata.url)
      //下面是书本的详情信息
      // cheerio  在node 里，使用jquery 的语法，来解析文档
      const $ = cheerio.load(detailPage.data)
      const info = $('#info').text().split('\n').map(v=>v.trim()).filter(v=>v)
      let author = info[1]
      let tags =[]
      $('#db-tags-section a.tag').each((i,v)=>{
        tags.push({
          title:$(v).text()
        })
      })
       const ret ={
         create_time:new Date().getTime(),
         title:searchdata.title,
         rate:searchdata.rating,
         image:searchdata.cover_url,
         url:searchdata.url,
         summary:$('#link-report .intro').text(),
         tags,
         author,
       }
      console.log(ret)
      return ret

  }
}
//本地调试入口
console.log(getdouban('9787121336775'))

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const {
    isbn
  } = event

  return getdouban(isbn)
}